package com.maycur.taskdemo.task.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
@Slf4j
public abstract class AbstractBaseTask implements SchedulingConfigurer {
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(
                //1.添加任务内容(Runnable)
                ()-> {
                    String localIp= null;
                    String  ip ="";//tyydConfigurations.properties.getProperty("task_ip");
                    try{
                        localIp = InetAddress.getLocalHost().getHostAddress();
                        if(StringUtils.isBlank(ip) || StringUtils.equals(ip,localIp)) {
                            doTast();
                        }
                    } catch (UnknownHostException e) {
                        log.error("获取本机IP失败"+e.getMessage());
                    } catch (Exception e1) {
                        log.error("定时任务执行失败"+e1.getMessage());
                    }
                },
                //2.设置执行周期(Trigger)
                triggerContext -> {
                    String  cron =getTaskProperties();//tyydConfigurations.properties.getProperty(getTaskProperties());
                    if(StringUtils.isBlank(cron)) {
                        cron="0 1 0 1 * ?";
                    }

                    Date d;
                    try {
                        //2.3 返回执行周期(Date)
                        d= new CronTrigger(cron).nextExecutionTime(triggerContext);
                    }catch (NumberFormatException e)
                    {
                        d= new CronTrigger("0 1 0 1 * ?").nextExecutionTime(triggerContext);
                    }

                    return d;
                }
        );
    }

    /**
     * 获取各个任务不同的执行时间
     * @return
     */
    protected abstract String getTaskProperties();

    /**
     * 具体任务调用实现
     */
    protected abstract void doTast();
}
